import apiUrl from '@/api/apiUrl'
import {Toast} from 'mint-ui'

export default {
    getUsers() {
        let params = {
            params: {
                room_id: sessionStorage.getItem('room_id'),
                row: 1000
            }
        }
        this.$http.get(apiUrl.api.roomOnlineUsers, params).then(res => {
            if (res.data.code === 0) {
                res.data.result.forEach(v=> {
                    this.users.push(v.user_name)
                })
            } else {
                Toast(res.data.msg)
            }
        })
    },
    getBetss() {
        let params = {
            params: {room_id: sessionStorage.getItem('room_id')}
        }
        this.$http.get(apiUrl.api.betss, params).then(res=> {
            if (res.data.code === 0) {
                this.$set(this, 'betss', res.data.result)
            }
        }).catch(err => {
            console.log(err)
        })
    },
    goldChange (gold) {
        this.userRoomInfoData.gold -= gold
    },
    getUserRoomInfo()
    {
        let params = {
            params: {
                room_id: sessionStorage.getItem('room_id')
            }
        }
        this.$http.get(apiUrl.api.userRoomInfo, params).then(res => {
            if (res.data.code === 0) {
                this.$set(this, 'userRoomInfoData', res.data.result)
            } else {
                Toast(res.data.msg)
            }
        }).catch(err => {
            console.log(err)
        })
    },
    getAwardData () {
        this.$http.get(apiUrl.api.getAwardData).then(res => {
            if (res.data.code === 0) {
                res.data.result.current.resultArr = res.data.result.current.result.split(',')
                this.$set(this, 'awardData', res.data.result)
            } else {
                Toast(res.data.msg)
            }
        }).catch(err => {
            Toast('网络错误，请刷新页面重试')
        })
    },
    allowEvent (v) {
        this.$set(this, 'allow', v)
    },
    send (msg) {
        // onsole.log(e)
        this.sendLoading = true
        let params = new URLSearchParams()
            params.append('room_id', sessionStorage.getItem('room_id'))
            params.append('user_id', sessionStorage.getItem('user_id'))
            params.append('user_name', sessionStorage.getItem('user_name'))
            params.append('msg', msg)

        let timeout = window.setTimeout(()=> {
            if (this.sendLoading === true) {
                this.sendLoading = false
                window.clearTimeout(timeout)
            }
        }, 5000)

        this.$http.post(apiUrl.websocket.send, params).then(res => {
            if (res.data.code === 0) {
                // 判断是否下单
                this.sendType(msg)
            } else {
                Toast('发送失败')
            }
            this.sendLoading = false
            window.clearTimeout(timeout)
        }).catch(err => {
            console.log(err.message)
        })
    },
    sendType(msg) {
        let cashReg = /^[下|回](\d+)$/;
        let claimReg = /^上(\d+)$/;

        if (msg.replace(cashReg, '').length === 0) { // ※提现金币※   格式:(下100)
            let matchs = msg.match(cashReg)
            let gold   = matchs[1]

            if (gold <= 0) {
                return system({msg: '提现金额必须大于0'}, this.$refs.chat);
            }

            if (gold > this.userRoomInfoData.gold) {
                return system({msg: `最大提现金额:${this.userGold.number}金币`}, this.$refs.chat);
            }

            let params = new URLSearchParams();
            params.append('room_id', sessionStorage.getItem('room_id'))
            params.append('number', gold)

            this.$http.post(apiUrl.api.cash, params).then(res => {
                if (res.data.code === 0) {
                    // 冻结金币
                    this.userRoomInfoData.gold -= gold
                    return system({msg: '已发送提现申请'}, this.$refs.chat);
                } else {
                    // Toast(res.data.msg)
                    return system(res.data, this.$refs.chat);
                }
            }).catch(err => console.log(err))

        } else if (msg.replace(claimReg, '').length === 0) { // 索取金币 格式:(上100)
            let matchs = msg.match(claimReg)
            let gold   = matchs[1]

            if (gold <= 0) {
                // return Toast(`金额必须大于0`)
                return system({msg: '索取金额必须大于0'}, this.$refs.chat);
            }

            let params = new URLSearchParams();
            params.append('room_id', sessionStorage.getItem('room_id'))
            params.append('gold', gold)
            this.$http.post(apiUrl.api.claimAdd, params).then(res => {
                if (res.data.code === 0) {
                    return system({msg: '已发送索取金币请求'}, this.$refs.chat);
                } else {
                    //Toast(res.data.msg)
                    return system(res.data, this.$refs.chat);
                }
            }).catch(err => console.log(err))
        } else {
            if (msg.indexOf('#') === -1) { // ※单个竞猜※
                let single = this.single(msg)
                if (single) {
                    this.addOrder(single.betss, single.amount)
                }
            } else { // ※组合竞猜※
                let arr = msg.split('#')
                let betss = []
                let amount = 0
                let isErr = false
                arr.forEach(str => {
                    let single = this.single(str)
                    if (!single) {
                        isErr = true
                    } else {
                        amount += single.amount
                        betss.concat(single.betss)
                    }
                })

                if (!isErr) {
                    this.addOrder(betss, amount)
                }
            }
        }
    },
    addOrder(betss, amount){
        if (!this.allow) {
            return system({msg: '当前时间不能下单'}, this.$refs.chat);
            // return Toast('当前时间不能下单.');
        }
        let params = new URLSearchParams()
        params.append('room_id', sessionStorage.getItem('room_id'))
        params.append('issue_no', this.awardData.next.period) // 期号
        params.append('amount', amount)
        params.append('betss', betss.join(','))

        this.$http.post(apiUrl.api.order, params).then(res => {
            if (res.data.code === 0) {
                this.goldChange(amount)
                // Toast('注单已加入队列');
            } else {
                Toast(res.data.msg);
            }
        }).catch(err => {
            Toast(err)
        })
    },
    single(msg) {
        // ※定位竞猜※   格式:(名次/号码/竞分)
        let positionReg = /^(\d+)\/([\d|单|双|大|小]+)\/(\d+)$/
        // 龙虎竞猜 格式:(名次/号码/竞分)
        let longHuReg = /^([1-5]+)\/([\d|单|双|大|小|龙|虎]+)\/(\d+)$/
        // 默认竞猜 格式:(号码/竞分)  默认冠军
        let defaultReg = /^([\d|单|双|大|小|龙|虎]+)\/(\d+)$/;
        // ※冠亚和竞猜※   例如:和/4/100,代表冠军和竞猜号码“4”,分数100
        let andReg = /^和\/((3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|单|双|大|小)+)\/(\d+)$/

        // 处理名次
        let ranking = function (rank) {
            let reg = /\d/g
            return rank.match(reg).map(v => {
                return v === "0" ? "10" : v
            })
        }

        // 处理号码
        let number = function (numbers, type='default') {
            let reg = null
            if (type === 'and') {
                reg = /(3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|单|双|大|小)/g
            } else {
                reg = /(\d|单|双|大|小|龙|虎)/g
            }
            return numbers.match(reg).map(v => {
                return v === "0" ? "10" : v
            })
        }

        let ogMtrans = function (ranking, number, betss) {
            let r = parseInt(ranking) - 1
            if (ranking === 'and') {
                r = 10
            }

            let n = parseInt(number) - 1
            // 冠亚军和
            if (r === 10) {
                switch (number) {
                    case '单':
                        n = 19
                        break;
                    case '双':
                        n = 20
                        break;
                    case '大':
                        n = 17
                        break;
                    case '小':
                        n = 18
                        break;
                    default:
                        n = parseInt(number) - 3
                }
            } else {
                switch (number) {
                    case '大':
                        n = 10
                        break;
                    case '小':
                        n = 11
                        break;
                    case '单':
                        n = 12
                        break;
                    case '双':
                        n = 13
                        break;
                    case '龙':
                        n = 14
                        break;
                    case '虎':
                        n = 15
                        break;
                    default:
                        n = parseInt(number) - 1
                }
            }

            return betss[r]['OgMtrans'][n]
        }

        // 下注名次数组
        let rankArr = []
        // 下注号码数组
        let numberArr = []
        // 下注金币
        let gold = 0

        if (msg.replace(positionReg, '').length === 0) {
            let matchs  = msg.match(positionReg)
            rankArr     = ranking(matchs[1])
            numberArr   = number(matchs[2])
            gold        = matchs[3]
        } else if (msg.replace(longHuReg, '').length === 0) {
            let matchs  = msg.match(longHuReg)
            rankArr     = ranking(matchs[1])
            numberArr   = number(matchs[2])
            gold        = matchs[3]
        } else if (msg.replace(defaultReg, '').length === 0) {
            let matchs  = msg.match(defaultReg)
            rankArr     = ["1"]
            numberArr   = number(matchs[1])
            gold        = matchs[2]
        } else if (msg.replace(andReg, '').length === 0) {
            let matchs  = msg.match(andReg)
            rankArr     = ["and"]
            numberArr   = number(matchs[1], 'and')
            gold        = matchs[3]
        } else {
            return false;
        }

        let betss = []

        // 名次|号码|金额|赔率|组号|objectId
        rankArr.forEach(rank => {
            numberArr.forEach(number => {
                let og = ogMtrans(rank, number, this.betss)
                let tmp = []
                tmp.push(rank)
                tmp.push(number)
                tmp.push(gold)
                tmp.push(og.odds)
                tmp.push(og.Groupno)
                tmp.push(og.Objectid)
                betss.push(tmp.join('|'))
            })
        })

        return {
            betss: betss,
            amount: betss.length * gold
        }
    },
    getOdds() {
        let params = {
            params: {
                room_id: sessionStorage.getItem('room_id')
            }
        }
        this.$http.get(apiUrl.api.odds, params).then(res => {
            if (res.data.code === 0) {
                if (res.data.result.odds) {
                    res.data.result.odds.forEach((v, k) => {
                        this.odds[v.item].push({
                            field: v.number,
                            odds: v.odds
                        })
                    })
                }
                this.defaultOdds = res.data.result.default
            } else {
                Toast('网络错误，请刷新页面重试')
            }
        })
    },
    chat () {
        let room_id = sessionStorage.getItem('room_id')
        let room_token = sessionStorage.getItem('room_token')
        let uid = sessionStorage.getItem('user_id')
        let user_name = sessionStorage.getItem('user_name')

        if (!room_id || !room_token) {
            this.$router.replace({name: 'factory-login'})
        } else {

            let proEnv = require('../../../../config/pro.env') // 生产环境
            let uatEnv = require('../../../../config/uat.env') // 测试环境
            let devEnv = require('../../../../config/dev.env') // 本地环境

            const env = process.env.NODE_ENV
            let wsUrl = ''
            // 默认本地环境
            if (env === 'production') {     // 生产环境
                wsUrl = proEnv.WEBSOCKT
            } else if (env === 'test') {    // 测试环境
                wsUrl = uatEnv.WEBSOCKT
            } else {                        // 本地环境
                wsUrl = devEnv.WEBSOCKT
            }
            this.ws = new WebSocket(wsUrl);

            this.ws.onopen = () => {
                console.log("Opened");
                let data = {
                    action: 'login',
                    room_id: sessionStorage.getItem('room_id'),
                    user_id: sessionStorage.getItem('user_id'),
                    user_name: sessionStorage.getItem('user_name'),
                    content: ''
                }
                this.ws.send(JSON.stringify(data));

                // window.setInterval(() => {
                //     this.ws.send(JSON.stringify(['p']))
                // }, 3000)
            }

            this.ws.onmessage = evt => {
                let res = JSON.parse(evt.data)
                switch (res.action) {
                    case 'login':
                        if (this.lockReconnect === false && this.connectWebsocket === false){
                            login(res, this.$refs.chat)
                            this.connectWebsocket = true
                        }
                        // this.users.push(res.user_name)
                        // this.users = this.users.filter(function (element, index, array) {
                        //     return array.indexOf(element) === index;
                        // })
                        //方法三  利用数组中的filter方法
                        let arr = this.users;
                        arr.push(res.user_name)
                        let r = arr.filter(function(element,index,self){
                            return self.indexOf(element) === index;
                        });
                        this.users = r

                        break
                    case 'logout':
                        this.users.forEach((v,k) => {
                            if (v === res.user_name) {
                                this.users.splice(k, 1)
                            }
                        })
                        break;
                    case 'chat':
                        chat(res, this.$refs.chat)
                        break
                    case 'system':
                        system(res, this.$refs.chat)
                        if (res.gold) {
                            if (res.flow === 1) {
                                this.userRoomInfoData.gold += parseInt(res.gold)
                            } else {
                                this.userRoomInfoData.gold -= parseInt(res.gold)
                            }
                        }

                        if (res.profit) {
                            if (res.flow === 1) {
                                this.userRoomInfoData.profit += parseInt(res.profit)
                            } else {
                                this.userRoomInfoData.profit -= parseInt(res.profit)
                            }
                        }

                        break

                }
                // console.log(res)
            }

            this.ws.onclose = () => {
                let data = {
                    action: 'logout',
                    room_id: room_id,
                    user_id: uid,
                    user_name: user_name,
                    content: ''
                }
                this.ws.send(JSON.stringify(data));
                console.log("Closed");
                if (this.$refs.chat) {
                    /*system({
                        msg: '网络链接错误，断开链接，5秒后自动尝试重链'
                    }, this.$refs.chat)*/
                    this.reconnect()
                }
            }

            this.ws.onerror = (err) => {
                // console.log("Error: " + err);
                // system({
                //     msg: '网络链接错误，断开链接，请刷新页面重试'
                // }, this.$refs.chat)
                this.reconnect()
            }
        }
    },
    reconnect() {
        if(this.lockReconnect) {
            return
        }

        this.lockReconnect = true

        //没连接上会一直重连，设置延迟避免请求过多
        this.tt && window.clearTimeout(this.tt);
        this.tt = window.setTimeout( () => {
            this.chat()
            this.lockReconnect = false
        }, 2000)
    },
    getActors() {
        let params = {
            params: {
                room_id: sessionStorage.getItem('room_id')
            }
        }
        this.$http.get(apiUrl.api.actors, params).then(res => {
            if (res.data.code === 0) {
                window.setTimeout(() => {
                    res.data.result.forEach(v => {
                        this.users.push(v.user_name)
                    })
                }, 1000)
            } else {
                Toast(res.data.msg);
            }
        })
    }
}

function system(res, e) {
    let ele = document.createElement('div')
    ele.className = 'system'
    ele.style.padding = '.5rem'
    ele.style.color = '#2C3E50'
    ele.innerHTML = `&#xe64c; 系统消息: ${res.msg} .`
    e.appendChild(ele)
    e.scrollTop = e.scrollHeight
}

/**
 * 登录
 * @param res
 * @param e
 */
function login(res, e) {
    let ele = document.createElement('div')
        ele.className = 'system'
        ele.style.padding = '.5rem'
        ele.style.color = '#2C3E50'
        ele.innerHTML = `&#xe64c; 系统消息: ${res.user_name} 进入聊天室.`
    e.appendChild(ele)
    e.scrollTop = e.scrollHeight
}

/**
 * 信息
 * @param res
 * @param e
 */
function chat(res, e) {
    let alert = document.createElement('div')
        alert.style.padding = '.5rem'
    let info = document.createElement('div')
        info.style.display = 'flex'
        info.style.justifyContent = 'flex-start'
        info.style.alignItems = 'baseline'
        info.style.color = '#2C3E50'
        let name = document.createElement('span')
            name.style.marginRight = '10px'
            if (parseInt(res.user_id) === parseInt(res.master)) {
                name.style.color = '#FF2045'
                name.innerHTML = '&#xe63c; 房主'
            } else {
                info.innerHTML = '&#xe604; ' + res.user_name
            }

        let time = document.createElement('span')
            time.style.fontSize = '.5rem'
            time.style.color = '#2C3E50'
            time.innerHTML = res.time

            info.appendChild(name)
            info.appendChild(time)
        alert.appendChild(info)
    let content = document.createElement('div')
        content.style.background = '#f1f1f1'
        content.style.borderRadius = '5px'
        content.style.textAlign = 'left'
        content.style.padding = '10px'
        content.style.marginTop = '5px'
        content.style.fontSize = '.85rem'
        content.style.lineHeight = '1.5rem'
        content.style.position = 'relative'
        let up = document.createElement('span')
            up.style.position = 'absolute'
            up.style.left = '10px'
            up.style.top = '-9px'
            up.style.width = '15px'
            up.style.height = '15px'
            up.style.lineHeight = '15px'
            up.style.color = '#f1f1f1'
            up.style.fontSize = '1.5rem'
            up.innerHTML = '&#xe613;'
            content.appendChild(up)
        let msg = document.createElement('span')
            msg.innerHTML = res.msg
            content.appendChild(msg)
        alert.appendChild(content)
    e.appendChild(alert)
    e.scrollTop = e.scrollHeight
}